<template>
  <div class="calling-wrap flex flex-col justify-center">
    <div class="calling flex flex-col justify-between py-60px">
      <div class="header text-white font-medium text-center">
        {{ type | headText(status) }}
      </div>
      <div class="content flex-1 flex-center">
        <div
          class="name text-white flex-center p-15px box-border text-center"
          :style="`background-color: ${userInfo.avatarBgc};`"
        >
          {{ studentInfo.name.slice(-2) }}家长
        </div>
      </div>
      <div class="footer flex justify-between" v-if="type === 'active'">
        <div class="item text-white flex flex-col items-center text-center" @click="switchMic">
          <img class="icon" :src="!isOpenMic ? Icons.micCloseIcon : Icons.micOpenIcon" mode="" />
          <span>{{ !isOpenMic ? '麦克风已关' : '麦克风已开' }}</span>
        </div>
        <div class="item text-white flex flex-col items-center text-center" @click="toHungup">
          <img class="icon" src="static/icons/hungup.png" mode="" />
          <span>{{ !isAccepted ? '取消' : '挂断' }}</span>
        </div>
        <div class="item text-white flex flex-col items-center text-center" @click="switchSpeaker">
          <img class="icon" :src="!isOpenSpeaker ? Icons.muteIcon : Icons.unMuteIcon" mode="" />
          <span>{{ !isOpenSpeaker ? '扬声器已关' : '扬声器已开' }}</span>
        </div>
      </div>
      <div
        class="footer flex justify-between"
        style="padding: 0 239.65rpx"
        v-else-if="type === 'passive'"
      >
        <div
          class="item text-white flex flex-col items-center text-center"
          @click="toAccept"
          v-show="!isAccepted"
        >
          <img class="icon" src="static/icons/accept.png" mode="" />
          <span>接听</span>
        </div>
        <div
          class="item text-white flex flex-col items-center text-center"
          @click="switchMic"
          v-show="isAccepted"
        >
          <img class="icon" :src="!isOpenMic ? Icons.micCloseIcon : Icons.micOpenIcon" mode="" />
          <span>{{ !isOpenMic ? '麦克风已关' : '麦克风已开' }}</span>
        </div>
        <div class="item text-white flex flex-col items-center text-center" @click="toHungup">
          <img class="icon" src="static/icons/hungup.png" mode="" />
          <span>{{ !isAccepted ? '取消' : '挂断' }}</span>
        </div>
        <div
          class="item text-white flex flex-col items-center text-center"
          @click="switchSpeaker"
          v-show="isAccepted"
        >
          <img class="icon" :src="!isOpenSpeaker ? Icons.muteIcon : Icons.unMuteIcon" mode="" />
          <span>{{ !isOpenSpeaker ? '扬声器已关' : '扬声器已开' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import IM from '@/im'
import micOpenIcon from '@/assets/icons/mic-open.png'
import micCloseIcon from '@/assets/icons/mic-close.png'
import muteIcon from '@/assets/icons/mute.png'
import unMuteIcon from '@/assets/icons/unmute.png'
import store from '@/store'
import { getStudentCallManage } from '@/api/contact'

const { IMEventType } = IM

export default {
  components: {},
  filters: {
    headText(type, status) {
      if (type === 'active') {
        switch (status) {
          case 0:
            return '拨号中…'
          case 1:
            return '已接通'
          case 2:
            return '已挂断…'
          default:
            return ''
        }
      } else if (type === 'passive') {
        switch (status) {
          case 0:
            return '邀请你语音通话…'
          case 1:
            return '已接通'
          case 2:
            return '已挂断…'
          default:
            return ''
        }
      }
    }
  },
  data() {
    return {
      $im: null,
      Icons: {
        micOpenIcon,
        micCloseIcon,
        muteIcon,
        unMuteIcon
      },
      type: '', // active => 主动拨打 passive => 被动接听
      status: 0, // 0 => 未接通 1 => 已接通 2 => 已挂断
      userInfo: {
        name: '',
        avatarBgc: ''
      },
      callManager: {
        vm: this._self,
        timer: null,
        promptEffect: {
          context: document.createElement('audio'),
          init: function () {
            this.context.src =
              'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/Di.mp3'
            this.context.currentTime = 0
          },
          play: function () {
            if (!this.context) return

            this.context.play()
          }
        },
        init: async function () {
          const { data } = await getStudentCallManage()
          const {
            callManageUsableVO: callManageUsable = [],
            callManageLimitVO: callManageLimit = []
          } = data

          if (callManageUsable.length === 0) return

          this.promptEffect.init()
          const getToday = () => {
            const today = '日一二三四五六'.charAt(new Date().getDay())

            switch (today) {
              case '日':
                return 7
              case '一':
                return 1
              case '二':
                return 2
              case '三':
                return 3
              case '四':
                return 4
              case '五':
                return 5
              case '六':
                return 6
              default:
                return
            }
          }

          const { endTime } = callManageUsable.find((i) => i.week == getToday())
          const endTimeStamp = new Date(
            `${this.vm.$utils.parseTime(new Date().getTime(), '{y}-{m}-{d}')} ${endTime}`
          ).getTime()
          let hasPrompt = false

          const task = () => {
            const nowTime = new Date().getTime()
            const remainder = (endTimeStamp - nowTime) / 1000

            if (!hasPrompt && remainder <= 300) {
              this.promptEffect.play()
              this.vm.$message.warning({
                message: `温馨提示，系统将于${Math.ceil(remainder / 60)}分钟后关闭语音通话`,
                offset: 20
              })
              hasPrompt = true
            }

            if (remainder <= 0) {
              this.vm.toHungup()
            }

            this.timer = setTimeout(() => {
              task()
            }, 1000)
          }

          task()
        },
        reset() {
          clearTimeout(this.timer)
        }
      },
      isOpenMic: true, // 麦克风状态
      isOpenSpeaker: false // 扬声器状态
    }
  },
  computed: {
    studentInfo() {
      const { im } = store.state
      const { userId, users } = im
      return users.find((u) => u.userId === userId)
    },
    isAccepted() {
      return this.status != 0
    }
  },
  watch: {
    isAccepted(newVal) {
      if (newVal) {
        this.callManager.init()
      }
    }
  },
  created() {
    this.$im = Vue.prototype.$im
  },
  mounted() {
    this.$im.on(this.IMListener)
  },
  beforeDestroy() {
    this.$im.off(this.IMListener)
  },
  methods: {
    IMListener(event) {
      const { type, data, msg } = event

      switch (type) {
        case IMEventType.CALL.acceptSuccess:
          this.status = 1
          break
        case IMEventType.CALL.onAccept:
          this.status = 1
          break
        case IMEventType.CALL.onTrackReady:
          if (this.isOpenSpeaker) {
            this.$im.openSpeaker()
          } else {
            this.$im.closeSpeaker()
          }
          break
        case IMEventType.CALL.onSessionClose:
          this.callManager.reset()
          break
        default:
          break
      }
    },
    switchMic() {
      if (this.isOpenMic) {
        this.isOpenMic = false
      } else {
        this.isOpenMic = true
      }
    },
    switchSpeaker() {
      if (this.isOpenSpeaker) {
        this.isOpenSpeaker = false

        if (this.isAccepted) {
          this.$im.closeSpeaker()
        }
      } else {
        this.isOpenSpeaker = true

        if (this.isAccepted) {
          this.$im.openSpeaker()
        }
      }
    },
    toAccept() {
      this.$im.accept()
    },
    toHungup() {
      Vue.prototype.$popup.hide('calling')
      this.$im.hungup()
    },
    setData({ type, data }) {
      this.type = type
      this.status = 0
      this.userInfo = data
    }
  }
}
</script>

<style lang="scss" scoped>
.calling-wrap {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.75);

  .calling {
    height: 100%;

    .header {
      font-size: 17.57px;
    }

    .content {
      .name {
        width: 100px;
        height: 100px;
        border-radius: 60px;
        font-size: 25px;
      }
    }

    .footer {
      height: auto;
      padding: 0 190px;
      background-color: transparent;

      .item {
        font-size: 24px;
        width: auto;
        min-height: 135px;

        .icon {
          width: 80px;
          height: 80px;
          margin-bottom: 20px;
        }
      }
    }
  }
}
</style>
